#include <sys/socket.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <pcap.h>

#define MAXLINE		10
#define OPEN_MAX	100
#define LISTENQ		20
#define SERV_PORT	5555
#define INFTIM		1000
int g_captureCount = 0;
int  MySetnonblocking(int fd)
{
	int opts;
	opts = fcntl(fd, F_GETFL);

	if(opts < 0) {
		return -1;
	}

	opts = opts | O_NONBLOCK;

	if(fcntl(fd, F_SETFL, opts) < 0) {
		return -1;
	}
}

int main(int argc, char *argv[])
{
	printf("epoll socket begins.\n");
	int i, maxi, pcapfd,epfd, nfds;
	ssize_t n;
	struct pcap_pkthdr pkthdr;        /* Packet information (timestamp,size...) */
	const unsigned char *packet=NULL;
	pcap_dumper_t *out_pcap;
	char errbuf[PCAP_ERRBUF_SIZE];
	char line[MAXLINE];

	//epoll create and initialie
	struct epoll_event ev, events[20];
	epfd = epoll_create(256);

	//create a fd and set non-block
	pcap_t* pcap = pcap_open_live("eth0", -1, false, -1, errbuf);
	if(pcap==NULL)
		printf("open failed\n");
	pcap_setnonblock(pcap, true, errbuf);

	struct bpf_program filter;
	pcap_compile(pcap, &filter, "udp port 7722", false, 0);
	pcap_setfilter(pcap, &filter);
	 out_pcap = pcap_dump_open(pcap, "./1.pcap");
        if(out_pcap==NULL)
        {
                fprintf(stderr,"open out_pcap failed!\n");
                return NULL;
        }

	pcap_freecode(&filter);

	pcapfd = pcap_get_selectable_fd(pcap);
	
	ev.data.fd = pcapfd;
	ev.events = EPOLLIN | EPOLLET;

	//add fd to epoll
	epoll_ctl(epfd, EPOLL_CTL_ADD, pcapfd, &ev);
	
	//process thread to do forword code
	for(; ;) {
		nfds = epoll_wait(epfd, events, 20, 500);

		for(i = 0; i < nfds; ++i) {
			if((events[i].data.fd) != -1 && events[i].events & EPOLLIN) {
				printf("capture a frame!\n");
				g_captureCount++;
				packet = pcap_next(pcap, &pkthdr);
				pcap_dump((u_char*)out_pcap, &pkthdr, packet);
			        pcap_dump_flush(out_pcap);
				printf("capture packet count is:%d\n", g_captureCount);
			}
		}
	}
}
